package com.zhaowenhao.hello.spring.framework.webmvc;

import com.zhaowenhao.hello.spring.framework.annotation.WHController;
import com.zhaowenhao.hello.spring.framework.annotation.WHRequestMapping;
import com.zhaowenhao.hello.spring.framework.context.WHApplicationContext;
import com.zhaowenhao.hello.spring.framework.webmvc.servlet.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description:
 * @Author: zwh
 * @Date: 2020-07-24
 * @Time: 16:43
 */
public class WHDispatcherServlet extends HttpServlet {

    private WHApplicationContext context = null;

    //handlerMapping
    private List<WHHandlerMapping> handlerMappings = new ArrayList<WHHandlerMapping>();

    //每个HandlerMapping对应一个handleradapter
    private Map<WHHandlerMapping, WHHandlerAdapter> handlerAdapters = new HashMap<WHHandlerMapping, WHHandlerAdapter>();

    //视图解析器，这里只有一个
    private List<WHViewResolver> viewResolvers = new ArrayList<WHViewResolver>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("hello-------------------------------------------------");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //1.拿到handler
        WHHandlerMapping handler = getHandler(req);

        //2 拿到适配器
        WHHandlerAdapter handlerAdapter = getHandlerAdapter(handler);

        //3. 在适配器中运行
        WHModelAndView mv = handlerAdapter.handle(req, resp, handler);

        //4渲染页面
        WHViewResolver whViewResolver = viewResolvers.get(0);
        whViewResolver.resolveViewName(mv.getViewName(), Locale.CHINESE);

        //5处理最终的结果
        processDispatchResult(req, resp, mv);

    }

    private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, WHModelAndView mv) throws Exception {
        String viewName = mv.getViewName();
        for (WHViewResolver viewResolver : viewResolvers) {
            WHView whView = viewResolver.resolveViewName(viewName, Locale.CHINESE);
            whView.render(mv.getModel(), req, resp);
            return;
        }
    }

    private WHHandlerAdapter getHandlerAdapter(WHHandlerMapping handler) {
        if (handlerAdapters.isEmpty()) {
            return null;
        }
        return handlerAdapters.get(handler);
    }

    private WHHandlerMapping getHandler(HttpServletRequest req) {
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        uri = uri.replace(contextPath, "").replaceAll("/+", "/");
        for (WHHandlerMapping handler : handlerMappings) {
            Matcher matcher = handler.getPattern().matcher(uri);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }


    @Override
    public void init(ServletConfig config) throws ServletException {

        //初始化ApplicationContexxt
        context = new WHApplicationContext(config.getInitParameter("contextConfigLocation"));

        initStrategies(context);

        System.out.println("WHSpring V4.0 is init...");

    }

    /**
     * 初始化九大组件，这里只初始化必要的三个组件：
     * handlerMapping handlerAdapter viewResolver
     *
     * @param context
     */
    private void initStrategies(WHApplicationContext context) {
        initHandlerMappings(context);
        initHandlerAdapters(context);
        initViewResolvers(context);
    }

    private void initViewResolvers(WHApplicationContext context) {
        String templateRoot = context.getConfig().get("templateRoot").toString();
        viewResolvers.add(new WHViewResolver(templateRoot));
    }

    private void initHandlerAdapters(WHApplicationContext context) {
        for (WHHandlerMapping handlerMapping : handlerMappings) {
            this.handlerAdapters.put(handlerMapping, new WHHandlerAdapter());
        }
    }

    private void initHandlerMappings(WHApplicationContext context) {
        String[] beanDefinitionNames = context.getBeanDefinitionNames();

        for (String beanDefinitionName : beanDefinitionNames) {
            Object controller = context.getBean(beanDefinitionName);
            Class<?> clazz = controller.getClass();
            if (!clazz.isAnnotationPresent(WHController.class)) {
                continue;
            }
            String baseUrl = "";

            if (clazz.isAnnotationPresent(WHRequestMapping.class)) {
                WHRequestMapping annotation = clazz.getAnnotation(WHRequestMapping.class);
                baseUrl = annotation.value();
            }

            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(WHRequestMapping.class)) {
                    continue;
                }
                WHRequestMapping whRequestMapping = method.getAnnotation(WHRequestMapping.class);
                String url = whRequestMapping.value();
                url = (baseUrl + "/" + url).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(url);
                WHHandlerMapping handlerMapping = new WHHandlerMapping(controller, method, pattern);
                handlerMappings.add(handlerMapping);

                System.out.println("Mapped" + baseUrl + "," + method);
            }
        }

    }


}
